package com.bac.rentmap.web.controller.osmimport;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bac.rentmap.osm.BuildingsReader;
import com.bac.rentmap.osm.StreetsReader;
import com.bac.rentmap.model.Building;
import com.bac.rentmap.model.Street;
import com.bac.rentmap.manager.BuildingManager;
import com.bac.rentmap.manager.StreetManager;

import java.util.List;

/**
 *
 * @author Ivan Holub
 */
public class OsmImportStreetsController extends SimpleFormController {

    private StreetsReader streetsReader;

    private StreetManager streetManager;

    public void setStreetsReader(StreetsReader streetsReader) {
        this.streetsReader = streetsReader;
    }

    public void setStreetManager(StreetManager streetManager) {
        this.streetManager = streetManager;
    }

    protected Object formBackingObject(HttpServletRequest httpServletRequest) throws Exception {

        int maxNumber = streetManager.getMaxNumber();

        httpServletRequest.setAttribute("maxNumber", maxNumber);

        return super.formBackingObject(httpServletRequest);
    }

    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {

        List<Street> streets = streetsReader.readStreets(getServletContext());

        OsmImportCommand command = (OsmImportCommand) o;

        int number = Integer.valueOf(command.getNumber());

        int maxNumber = streetManager.getMaxNumber();

        int fromIndex = maxNumber;
        int toIndex = maxNumber + number;
        if (fromIndex < streets.size()) {
            if (toIndex > streets.size()) {
                toIndex = streets.size();
            }
            streets = streets.subList(fromIndex, toIndex);

            streetManager.saveStreets(streets);
        }

        maxNumber = streetManager.getMaxNumber();

        httpServletRequest.setAttribute("maxNumber", maxNumber);

        return super.onSubmit(httpServletRequest, httpServletResponse, o, e);
    }

    protected void initBinder(HttpServletRequest httpServletRequest, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }


}